package com.atguigu.spzx.manager.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.service.utils.AuthContextUtil;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.mysql.cj.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //权限验证  (拦截器)
    //配置类   (1. 拦截范围  2.跨域   )
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求方法
        String method = request.getMethod();
        //判断是否为预检测请求
        if("OPTIONS".equals(method)){
            return true;
        }
        //从请求头获取token
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            noLoginResponse(response);
            return  false;
        }
        //根据token从redis中获取用户信息
        String s = redisTemplate.opsForValue().get("user:login:" + token);
        if (StrUtil.isEmpty(s)) {
            noLoginResponse(response);
            return false;
        }
        SysUser sysUser = JSONObject.parseObject(s, SysUser.class);
        AuthContextUtil.set(sysUser);
        redisTemplate.expire("user:login:" + token , 2 , TimeUnit.HOURS) ;

        return true;
    }

    private void noLoginResponse(HttpServletResponse response) {
        Result result=Result.build(null, ResultCodeEnum.NO_AUTH);
        response.setContentType("text/html; charset=UTF-8");
        try {
            PrintWriter writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();
    }
}
